package com.sys.dao.impl;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.sys.dao.DownLoadDao;
import com.sys.domain.Download;
import com.sys.service.UploadOperationSer;
import com.sys.service.impl.UploadOperationImpl;
import com.sys.utils.C3P0Utils;

public class DownLoadImpl implements DownLoadDao {
	private QueryRunner queryRunner;
	public DownLoadImpl() {
		queryRunner = new QueryRunner(C3P0Utils.getDataSource());
	}
	@Override
	public Boolean insertDownLoad(Download download) throws SQLException {
		String sql = "insert into download values(?,?,?)";
		int row = queryRunner.update(sql, download.getFileId(), download.getUserId(), download.getDownTime());
		return row>0?true:false;
	}

	@Override
	public Boolean deleteDownLoadRecord(Download download) throws SQLException {
		String sql = "delete from download where user_id = ? and down_time = ?";
		int row = queryRunner.update(sql, download.getUserId(), download.getDownTime());
		return row>0?true:false;
	}

	@Override
	public List<Download> findSelfDownRecord(String userId) throws SQLException {
		String sql = "select file_id as fileId, user_id as userId, down_time as downTime from download where user_id = ?";
		List<Download> downRecords = queryRunner.query(sql, new BeanListHandler<Download>(Download.class), userId);
		UploadOperationSer uOS = new UploadOperationImpl();
		for(Download eDownload :downRecords) {
			eDownload.setFileId(uOS.deleteUserIdOfFile(eDownload.getFileId()));
		}
		Collections.sort(downRecords);
		return downRecords;
	}

}
